{% extends "base.html" %}

{% block content %}
<div class="max-w-4xl mx-auto">
    <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900">Upload Document</h1>
        <p class="text-gray-600">Add new regulatory documents to the knowledge base</p>
    </div>

    <div id="errorSummary" class="hidden mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
        <div class="flex items-start space-x-3">
            <i class="fas fa-exclamation-triangle text-red-600 text-xl mt-1"></i>
            <div class="flex-1">
                <p class="font-medium text-red-900">Please correct the following errors:</p>
                <ul id="errorList" class="mt-2 text-sm text-red-700 list-disc list-inside"></ul>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <form id="uploadForm" enctype="multipart/form-data">
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">Document File <span class="text-red-500">*</span></label>
                <div id="fileUploadArea" class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors">
                    <input 
                        type="file" 
                        id="fileInput"
                        name="file"
                        accept=".pdf,.doc,.docx,.xlsx,.txt"
                        class="hidden"
                    >
                    <div id="uploadArea" class="cursor-pointer">
                        <div class="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center mx-auto mb-3">
                            <i class="fas fa-file-upload text-gray-600 text-xl"></i>
                        </div>
                        <p class="text-gray-600 mb-1">
                            <span class="text-indigo-600 font-medium">Click to upload</span> or drag and drop
                        </p>
                        <p class="text-sm text-gray-500">PDF, DOC, DOCX, XLSX, TXT (Max 50MB)</p>
                    </div>
                    <div id="fileInfo" class="hidden">
                        <div class="flex items-center justify-center space-x-2 mb-2">
                            <i class="fas fa-check-circle text-green-600 text-xl"></i>
                            <span class="font-medium text-gray-900" id="fileName"></span>
                        </div>
                        <button 
                            type="button" 
                            onclick="clearFile()"
                            class="text-sm text-red-600 hover:text-red-800"
                        >
                            Remove file
                        </button>
                    </div>
                </div>
                <p id="fileError" class="hidden mt-2 text-sm text-red-600"></p>
                <p id="fileTypeError" class="hidden mt-2 text-sm text-red-600"></p>
            </div>

            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">File Name <span class="text-red-500">*</span></label>
                <input 
                    type="text" 
                    name="file_name"
                    id="fileNameInput"
                    placeholder="Enter file name (letters, numbers, ., _, - only)"
                    maxlength="128"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    required
                >
                <p id="file_nameError" class="hidden mt-2 text-sm text-red-600"></p>
                <p class="mt-1 text-sm text-gray-500">Only letters, numbers, dots (.), underscores (_), and hyphens (-) are allowed. Max 128 characters.</p>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Country/Region <span class="text-red-500">*</span></label>
                    <select 
                        name="country"
                        id="countrySelect"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                        <option value="">Select Country</option>
                    </select>
                    <p id="countryError" class="hidden mt-2 text-sm text-red-600"></p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Document Type <span class="text-red-500">*</span></label>
                    <select 
                        name="document_type"
                        id="documentType"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                        <option value="">Select Type</option>
                        <option value="pdf">PDF</option>
                        <option value="doc">DOC</option>
                        <option value="docx">DOCX</option>
                        <option value="xlsx">XLSX</option>
                        <option value="txt">TXT</option>
                    </select>
                    <p id="document_typeError" class="hidden mt-2 text-sm text-red-600"></p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Regulation ID</label>
                    <input 
                        type="text" 
                        name="regulation_id"
                        id="regulationId"
                        placeholder="e.g., 21 CFR 820, ISO 13485"
                        maxlength="64"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    >
                    <p id="regulation_idError" class="hidden mt-2 text-sm text-red-600"></p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Issuing Authority <span class="text-red-500">*</span></label>
                    <input 
                        type="text" 
                        name="issuing_authority"
                        id="issuingAuthority"
                        placeholder="e.g., FDA, NMPA, ISO"
                        maxlength="64"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                    <p id="issuing_authorityError" class="hidden mt-2 text-sm text-red-600"></p>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Collection <span class="text-red-500">*</span></label>
                    <select 
                        name="collection"
                        id="collectionSelect"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                        <option value="">Select Collection</option>
                    </select>
                    <p id="collectionError" class="hidden mt-2 text-sm text-red-600"></p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Status <span class="text-red-500">*</span></label>
                    <select 
                        name="status"
                        id="statusSelect"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                        <option value="">Select Status</option>
                        <option value="Draft">Draft</option>
                        <option value="Effective">Effective</option>
                        <option value="Expired">Expired</option>
                    </select>
                    <p id="statusError" class="hidden mt-2 text-sm text-red-600"></p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Effective Date <span class="text-red-500">*</span></label>
                    <input 
                        type="date" 
                        name="effective_date"
                        id="effectiveDate"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                    <p id="effective_dateError" class="hidden mt-2 text-sm text-red-600"></p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Version</label>
                    <input 
                        type="text" 
                        name="version"
                        id="version"
                        placeholder="e.g., v1.2, 2024 edition"
                        maxlength="32"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    >
                    <p id="versionError" class="hidden mt-2 text-sm text-red-600"></p>
                </div>
            </div>

            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">Tags</label>
                <div class="relative">
                    <input 
                        type="text" 
                        id="tagInput"
                        placeholder="Type and press Enter to add tags"
                        maxlength="32"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        autocomplete="off"
                    >
                    <input type="hidden" name="tags" id="tagsHidden">
                    <div id="tagSuggestions" class="hidden absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-48 overflow-y-auto"></div>
                </div>
                <div id="tagContainer" class="mt-2 flex flex-wrap gap-2"></div>
                <p id="tagsError" class="hidden mt-2 text-sm text-red-600"></p>
                <p class="mt-1 text-sm text-gray-500">Press Enter to add tags. Maximum 8 tags allowed.</p>
            </div>

            <div class="flex items-center justify-end space-x-4">
                <button 
                    type="button"
                    onclick="location.href='/documents'"
                    class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                >
                    Cancel
                </button>
                <button 
                    type="submit"
                    class="px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 flex items-center space-x-2"
                    id="submitButton"
                >
                    <i class="fas fa-cloud-upload-alt"></i>
                    <span>Upload Document</span>
                </button>
            </div>
        </form>
    </div>

    <div id="uploadStatus" class="hidden mt-6"></div>
</div>
{% endblock %}

{% block scripts %}
<script>
let selectedTags = [];
const MAX_TAGS = 8;
const TAG_COLORS = ['bg-blue-100 text-blue-800', 'bg-green-100 text-green-800', 'bg-purple-100 text-purple-800', 
                    'bg-pink-100 text-pink-800', 'bg-yellow-100 text-yellow-800', 'bg-indigo-100 text-indigo-800'];

document.addEventListener('DOMContentLoaded', async () => {
    await loadCountries();
    await loadCollections();
    setupFileHandling();
    setupFormValidation();
});

async function loadCountries() {
    try {
        const response = await fetch('/api/countries');
        const data = await response.json();
        if (data.status === 'success') {
            const select = document.getElementById('countrySelect');
            data.countries.forEach(country => {
                const option = document.createElement('option');
                option.value = country.name;
                option.textContent = country.name;
                select.appendChild(option);
            });
        }
    } catch (error) {
        console.error('Error loading countries:', error);
    }
}

async function loadCollections() {
    try {
        const response = await fetch('/api/collections/list');
        const data = await response.json();
        if (data.status === 'success') {
            const select = document.getElementById('collectionSelect');
            data.collections.forEach(collection => {
                const option = document.createElement('option');
                option.value = collection.name;
                option.textContent = collection.display_name || collection.name;
                select.appendChild(option);
            });
        }
    } catch (error) {
        console.error('Error loading collections:', error);
    }
}

function setupFileHandling() {
    const fileInput = document.getElementById('fileInput');
    const uploadArea = document.getElementById('uploadArea');
    const fileInfo = document.getElementById('fileInfo');
    const fileName = document.getElementById('fileName');
    
    uploadArea.addEventListener('click', () => fileInput.click());
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('border-indigo-400', 'bg-indigo-50');
    });
    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('border-indigo-400', 'bg-indigo-50');
    });
    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('border-indigo-400', 'bg-indigo-50');
        if (e.dataTransfer.files.length) {
            fileInput.files = e.dataTransfer.files;
            handleFileSelect(e.dataTransfer.files[0]);
        }
    });
    
    fileInput.addEventListener('change', (e) => {
        if (e.target.files.length) {
            handleFileSelect(e.target.files[0]);
        }
    });
}

function handleFileSelect(file) {
    const maxSize = 50 * 1024 * 1024;
    const allowedTypes = ['.pdf', '.doc', '.docx', '.xlsx', '.txt'];
    const fileExt = '.' + file.name.split('.').pop().toLowerCase();
    
    clearFieldError('file');
    clearFieldError('file_type');
    
    if (file.size > maxSize) {
        showFieldError('file', 'Document size cannot exceed 50MB');
        document.getElementById('fileInput').value = '';
        return;
    }
    
    if (!allowedTypes.includes(fileExt)) {
        showFieldError('file_type', 'File type must be PDF, DOC, DOCX, XLSX, or TXT');
        document.getElementById('fileInput').value = '';
        return;
    }
    
    document.getElementById('fileName').textContent = file.name;
    document.getElementById('uploadArea').classList.add('hidden');
    document.getElementById('fileInfo').classList.remove('hidden');
    
    const baseName = file.name.replace(/\.[^/.]+$/, "");
    document.getElementById('fileNameInput').value = baseName;
}

function clearFile() {
    document.getElementById('fileInput').value = '';
    document.getElementById('uploadArea').classList.remove('hidden');
    document.getElementById('fileInfo').classList.add('hidden');
    clearFieldError('file');
    clearFieldError('file_type');
    document.getElementById('fileNameInput').value = '';
}

const tagInput = document.getElementById('tagInput');
const tagSuggestions = document.getElementById('tagSuggestions');

tagInput.addEventListener('input', async (e) => {
    const query = e.target.value.trim();
    if (query.length === 0) {
        tagSuggestions.classList.add('hidden');
        return;
    }
    
    try {
        const response = await fetch(`/api/tags?search=${encodeURIComponent(query)}`);
        const data = await response.json();
        if (data.status === 'success' && data.tags.length > 0) {
            showTagSuggestions(data.tags);
        }
    } catch (error) {
        console.error('Error fetching tags:', error);
    }
});

function showTagSuggestions(tags) {
    tagSuggestions.innerHTML = '';
    const filteredTags = tags.filter(tag => !selectedTags.includes(tag));
    
    if (filteredTags.length === 0) {
        tagSuggestions.classList.add('hidden');
        return;
    }
    
    filteredTags.forEach(tag => {
        const div = document.createElement('div');
        div.className = 'px-4 py-2 hover:bg-gray-100 cursor-pointer';
        div.textContent = tag;
        div.onclick = () => addTag(tag);
        tagSuggestions.appendChild(div);
    });
    
    tagSuggestions.classList.remove('hidden');
}

tagInput.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
        e.preventDefault();
        const tag = tagInput.value.trim();
        if (tag) addTag(tag);
    }
});

function addTag(tag) {
    if (selectedTags.length >= MAX_TAGS || selectedTags.includes(tag)) return;
    
    const tagPattern = /^[A-Za-z0-9]+$/;
    if (!tagPattern.test(tag) || tag.length > 32) return;
    
    selectedTags.push(tag);
    renderTags();
    tagInput.value = '';
    tagSuggestions.classList.add('hidden');
    document.getElementById('tagsHidden').value = selectedTags.join(',');
    clearFieldError('tags');
}

function removeTag(tag) {
    selectedTags = selectedTags.filter(t => t !== tag);
    renderTags();
    document.getElementById('tagsHidden').value = selectedTags.join(',');
}

function renderTags() {
    const container = document.getElementById('tagContainer');
    container.innerHTML = '';
    selectedTags.forEach((tag, index) => {
        const colorClass = TAG_COLORS[index % TAG_COLORS.length];
        const tagEl = document.createElement('span');
        tagEl.className = `inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${colorClass}`;
        tagEl.innerHTML = `${tag}<button type="button" onclick="removeTag('${tag}')" class="ml-2 focus:outline-none"><i class="fas fa-times text-xs"></i></button>`;
        container.appendChild(tagEl);
    });
}

function setupFormValidation() {
    const inputs = document.querySelectorAll('input, select');
    inputs.forEach(input => {
        input.addEventListener('input', () => {
            const fieldName = input.name;
            clearFieldError(fieldName);
        });
        
        input.addEventListener('change', () => {
            const fieldName = input.name;
            clearFieldError(fieldName);
        });
    });
}

function showFieldError(fieldName, message) {
    document.getElementById('errorSummary').classList.add('hidden');
    
    let element, errorElement;
    
    switch(fieldName) {
        case 'file':
            element = document.getElementById('fileUploadArea');
            errorElement = document.getElementById('fileError');
            break;
        case 'file_type':
            element = document.getElementById('fileUploadArea');
            errorElement = document.getElementById('fileTypeError');
            break;
        case 'file_name':
            element = document.getElementById('fileNameInput');
            errorElement = document.getElementById('file_nameError');
            break;
        case 'country':
            element = document.getElementById('countrySelect');
            errorElement = document.getElementById('countryError');
            break;
        case 'document_type':
            element = document.getElementById('documentType');
            errorElement = document.getElementById('document_typeError');
            break;
        case 'regulation_id':
            element = document.getElementById('regulationId');
            errorElement = document.getElementById('regulation_idError');
            break;
        case 'issuing_authority':
            element = document.getElementById('issuingAuthority');
            errorElement = document.getElementById('issuing_authorityError');
            break;
        case 'collection':
            element = document.getElementById('collectionSelect');
            errorElement = document.getElementById('collectionError');
            break;
        case 'status':
            element = document.getElementById('statusSelect');
            errorElement = document.getElementById('statusError');
            break;
        case 'effective_date':
            element = document.getElementById('effectiveDate');
            errorElement = document.getElementById('effective_dateError');
            break;
        case 'version':
            element = document.getElementById('version');
            errorElement = document.getElementById('versionError');
            break;
        case 'tags':
            element = document.getElementById('tagInput');
            errorElement = document.getElementById('tagsError');
            break;
        default:
            return;
    }
    
    if (element) {
        element.classList.add('border-red-500', 'border-2');
        element.classList.remove('border-gray-300');
    }
    
    if (errorElement) {
        errorElement.textContent = message;
        errorElement.classList.remove('hidden');
    }
}

function clearFieldError(fieldName) {
    let element, errorElement;
    
    switch(fieldName) {
        case 'file':
            element = document.getElementById('fileUploadArea');
            errorElement = document.getElementById('fileError');
            break;
        case 'file_type':
            element = document.getElementById('fileUploadArea');
            errorElement = document.getElementById('fileTypeError');
            break;
        case 'file_name':
            element = document.getElementById('fileNameInput');
            errorElement = document.getElementById('file_nameError');
            break;
        case 'country':
            element = document.getElementById('countrySelect');
            errorElement = document.getElementById('countryError');
            break;
        case 'document_type':
            element = document.getElementById('documentType');
            errorElement = document.getElementById('document_typeError');
            break;
        case 'regulation_id':
            element = document.getElementById('regulationId');
            errorElement = document.getElementById('regulation_idError');
            break;
        case 'issuing_authority':
            element = document.getElementById('issuingAuthority');
            errorElement = document.getElementById('issuing_authorityError');
            break;
        case 'collection':
            element = document.getElementById('collectionSelect');
            errorElement = document.getElementById('collectionError');
            break;
        case 'status':
            element = document.getElementById('statusSelect');
            errorElement = document.getElementById('statusError');
            break;
        case 'effective_date':
            element = document.getElementById('effectiveDate');
            errorElement = document.getElementById('effective_dateError');
            break;
        case 'version':
            element = document.getElementById('version');
            errorElement = document.getElementById('versionError');
            break;
        case 'tags':
            element = document.getElementById('tagInput');
            errorElement = document.getElementById('tagsError');
            break;
        default:
            return;
    }
    
    if (element) {
        element.classList.remove('border-red-500', 'border-2');
        element.classList.add('border-gray-300');
    }
    
    if (errorElement) {
        errorElement.classList.add('hidden');
    }
}

function clearAllErrors() {
    const fields = [
        'file', 'file_type', 'file_name', 'country', 'document_type', 
        'regulation_id', 'issuing_authority', 'collection', 'status', 
        'effective_date', 'version', 'tags'
    ];
    
    fields.forEach(field => clearFieldError(field));
    document.getElementById('errorSummary').classList.add('hidden');
}

function displayServerErrors(errors) {
    clearAllErrors();
    
    if (!errors || Object.keys(errors).length === 0) {
        return;
    }
    
    const errorSummary = document.getElementById('errorSummary');
    const errorList = document.getElementById('errorList');
    errorList.innerHTML = '';
    
    Object.keys(errors).forEach(field => {
        const errorMessage = errors[field];
        showFieldError(field, errorMessage);
        
        const li = document.createElement('li');
        li.textContent = errorMessage;
        errorList.appendChild(li);
    });
    
    errorSummary.classList.remove('hidden');
    errorSummary.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

document.getElementById('uploadForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    
    // Convert date to yyyy/mm/dd format
    const dateInput = document.getElementById('effectiveDate');
    if (dateInput.value) {
        const date = new Date(dateInput.value);
        const formattedDate = `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`;
        formData.set('effective_date', formattedDate);
    }
    
    const submitButton = document.getElementById('submitButton');
    const uploadStatus = document.getElementById('uploadStatus');
    
    clearAllErrors();
    
    submitButton.disabled = true;
    submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>Uploading...</span>';
    uploadStatus.classList.remove('hidden');
    uploadStatus.innerHTML = `
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div class="flex items-center space-x-3">
                <i class="fas fa-spinner fa-spin text-blue-600 text-xl"></i>
                <div><p class="font-medium text-blue-900">Processing Document</p></div>
            </div>
        </div>
    `;
    
    try {
        const response = await fetch('/api/documents/upload', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.status === 'success') {
            uploadStatus.innerHTML = `
                <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                    <div class="flex items-center space-x-3">
                        <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        <div>
                            <p class="font-medium text-green-900">Document Uploaded Successfully</p>
                        </div>
                    </div>
                </div>
            `;
            
            setTimeout(() => {
                location.href = '/documents';
            }, 2000);
            
        } else {
            if (data.errors) {
                displayServerErrors(data.errors);
            }
            
            uploadStatus.innerHTML = `
                <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div class="flex items-center space-x-3">
                        <i class="fas fa-times-circle text-red-600 text-xl"></i>
                        <div><p class="font-medium text-red-900">Upload Failed</p><p class="text-sm text-red-700">${data.message || 'Unknown error occurred'}</p></div>
                    </div>
                </div>
            `;
        }
    } catch (error) {
        uploadStatus.innerHTML = `
            <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                <div class="flex items-center space-x-3">
                    <i class="fas fa-times-circle text-red-600 text-xl"></i>
                    <div><p class="font-medium text-red-900">Upload Failed</p><p class="text-sm text-red-700">Network error: ${error.message}</p></div>
                </div>
            </div>
        `;
    } finally {
        submitButton.disabled = false;
        submitButton.innerHTML = '<i class="fas fa-cloud-upload-alt"></i><span>Upload Document</span>';
        uploadStatus.classList.remove('hidden');
    }
});

document.addEventListener('click', (e) => {
    if (!tagInput.contains(e.target) && !tagSuggestions.contains(e.target)) {
        tagSuggestions.classList.add('hidden');
    }
});
</script>
{% endblock %}